<?php
/**
 * Created by PhpStorm.
 * User: kcj
 * Date: 2017/7/16
 * Time: 11:42
 */
namespace app\index\controller;

use think\Controller;
use think\Request;

require_once APP_PATH."common/wxlib/WxPay.Api.php";
require_once APP_PATH."common/WxPay.JsApiPay.php";
require_once APP_PATH."common/PayNotifyCallBack.php";
require_once APP_PATH."common/wxlib/log.php";

class Agency extends Controller
{
    public function index()
    {
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('bagency,id,openid,nickname,diamond,headimgurl')->where("openid='{$openId}'")->find();
        $this->assign("user",$user);
        $this->assign('oid',$openId);
        if($user['bagency'])
        {
            $list =db('recharge r')->limit(10)
                ->order('money desc,u.id asc')
                ->where('u.bagency=1')
                //->where('DATE_FORMAT(r.paytime,\'%Y%m\')=DATE_FORMAT(CURDATE(),"%Y%m")')
                ->join('ms_user u','u.openid=r.uid')
                ->field('sum(r.money) as money,u.nickname as name,u.headimgurl,u.id as id')
                ->group('r.uid')
                ->select();
            foreach ($list as $k=>$v)
            {
                $list[$k]['id']=substr_replace($v['id'],'***',2,3);
            }
            $u =db('recharge')
                ->where("uid='{$openId}'")
                ->where('DATE_FORMAT(paytime,\'%Y%m\')=DATE_FORMAT(CURDATE(),"%Y%m")')
                ->field('sum(money) as money')
                ->group('uid')
                ->find();
            $this->assign('money',$u['money']);
            $this->assign('url',url('index/agency','',false));
            $this->assign('recordlisturl',url('index/agency/rechargerecord','',false));
            $this->assign('transferlisturl',url('index/agency/transferrecord','',false));
            $this->assign('rechargeurl',url('index/agency/recharge','',false));
            $this->assign('transferurl',url('index/agency/transfer','',false));
            $this->assign('list',$list);
            return view('/agentindex');
        }
        else{
            $this->assign("formurl",url('/index/agency/pay','',false));
            $this->assign('urlsuccess',url('/index/agency/information','',false));
            return view('/firstcharge');
        }
    }

    public function transferrecord()
    {
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

//①、获取用户openid
        if(Request::instance()->isPost()) {
            $openId = $_POST['oid'];
        }
        else{
            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();
        }
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('id')->where("openid='{$openId}'")->find();

        $id=$_POST['id'];
        if(!empty($id))
        {
            $where['accepterid']=$id;
        }
        $where['transfererid']=$user['id'];

        $list = db('transfer')->where($where)->select();

        $diamond = 0;
        foreach($list as $k=>$v)
        {
            $list[$k]['date']=date("Y-m-d",strtotime($v['time']));
            $list[$k]['time']=date("H:i:s",strtotime($v['time']));
            $diamond+=$v['diamond'];
        }
        $this->assign('id',$id);
        $this->assign('oid',$openId);
        $this->assign('diamond',$diamond);
        $this->assign('url',url('/index/agency','',false));
        $this->assign('list',$list);

        return view('/attornRecord');
    }

    public function recharge()
    {
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('bagency,id,openid,nickname,diamond,headimgurl')->where("openid='{$openId}'")->find();
        $this->assign("user",$user);
        $this->assign('oid',$openId);

        $list =db('recharge')
            ->where("uid='{$openId}'")
            ->where('DATE_FORMAT(paytime,\'%Y%m\')=DATE_FORMAT(CURDATE(),"%Y%m")')
            ->field('sum(money) as money')
            ->group('uid')
            ->find();
        $this->assign('money',$list['money']);
        $this->assign("formurl",url('/index/agency/pay','',false));
        $this->assign('url',url('/index/agency','',false));
        return view('/agencyrecharge');
    }

    public function transfer()
    {
        if(Request::instance()->isPost())
        {
            $this->transferpost();
            return;
        }
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('bagency,id,openid,nickname,diamond,headimgurl')->where("openid='{$openId}'")->find();
        $this->assign("user",$user);
        $this->assign('oid',$openId);
        $this->assign('url',url('/index/agency','',false));
        return view('/attorn');
    }

    public function transferpost()
    {
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $openId = $_POST['oid'];
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('bagency,id,openid,diamond')->where("openid='{$openId}'")->find();
        $diamond = $_POST['diamond'];
        $uid=$_POST['uid'];
        $url=url('index/agency/transfer','',false);
        if($user['bagency']!==1)
        {
            $this->error('您不是代理商，不能进行该操作!',$url);
            return false;
        }
        if(empty($diamond))
        {
            $this->error('请填写钻石数目!',$url);
            return false;
        }
        if(empty($uid))
        {
            $this->error('请填写转入用户ID',$url);
            return false;
        }
        if(db('user')->where("id={$uid}")->count()!==1)
        {
            $this->error('该用户不存在！',$url);
            return false;
        }
        if($user['diamond']<$diamond)
        {
            $this->error("请输入小于{$user['diamond']}的钻石数！",$url);
            return false;
        }

        $user['diamond']-=$diamond;
        db('user')->update($user);
        $user2 = db('user')->field('diamond,id')->where("id={$uid}")->find();
        $user2['diamond']+=$diamond;
        db('user')->update($user2);
        $data['transfererid']=$user['id'];
        $data['accepterid']=$user2['id'];
        $data['diamond']=$diamond;
        $data['surplus']=$user['diamond'];
        $data['time']=date('Y-m-d H:i:s',time());
        if(false===db('transfer')->insert($data))
        {
            $this->error('转让记录添加失败！',$url);
            return false;
        }
        $this->success("成功向{$uid}转入{$diamond}颗钻石",url('/index/agency','',false));
        return true;
    }

    public function information()
    {
        if(Request::instance()->isPost())
        {
            $this->informationpost();
        }
        $this->assign('formurl',url('/index/agency/information','',false));
        return view("/information");
    }

    public function informationpost()
    {
        ini_set('date.timezone', 'Asia/Shanghai');
        $logHandler = new \CLogFileHandler(LOG_PATH . "wxpaylogs/" . date('Y-m-d') . '.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //$openId = "oibzjw4L_q2FGufK6hNBjTc82i-y";

        $user = db('user')->field('bagency,id,openid,nickname,diamond,headimgurl')->where("openid='{$openId}'")->find();

        if (!$user['bagency']) {
            $this->error('您还没有成为代理！');
            return false;
        }

        $code = $_POST['referrercode'];
        if (!empty($code)) {
            $exworker = db('exworker')->where("refereecode=$code")->find();
            if ($exworker == null) {
                $this->error("该推荐码有误，请输入正确的推广码！");
                return false;
            }
            if ($exworker['status'] !== 0) {
                $this->error("该推广人员已被停止使用！");
                return false;
            }
            $user['refereeid'] = $exworker['id'];
        }
        if (empty($_POST['username'])) {
            $this->error("姓名不能为空！");
            return false;
        }
        if (empty($_POST['phone'])) {
            $this->error("联系电话不能为空！");
            return false;
        }
        $user['name'] = $_POST['username'];
        $user['phone'] = $_POST['phone'];
        db('user')->where("id={$user['id']}")->update($user);
        $this->success('添加成功', url('/index/agency/index', '', false));
    }

    public function rechargerecord()
    {
        ini_set('date.timezone','Asia/Shanghai');
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //$openId="oibzjw4L_q2FGufK6hNBjTc82i-y";

        $list = db('recharge')->where("uid='$openId'")
            ->select();
        $money=0;
        $diamond=0;
        foreach($list as $k=>$v)
        {
            $strtimes = explode(" ",$list[$k]['paytime']);
            $list[$k]['paytime1']=$strtimes[0];
            $list[$k]['paytime2']=$strtimes[1];
            $money+=$v['money'];
            $diamond+=$v['diamond'];
        }
        $this->assign('money',$money);
        $this->assign('diamond',$diamond);  
        $this->assign('list',$list);
        $this->assign('url',url('/index/agency','',false));
        return view('/rechargeRecord');
    }

    public function pay()
    {
        $id = $_REQUEST['rcid'];
        $openId = $_REQUEST['oid'];
        ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
//初始化日志
        $logHandler= new \CLogFileHandler(LOG_PATH."wxpaylogs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);


//①、获取用户openid
        $tools = new \JsApiPay();

        $user = db('user')->where("openid='{$openId}'")->find();
        $count = db('user')->alias('u')->join('rechargeuserconfig r','u.usertype = r.usertype')->count();
        if($count==0)
        {
            $this->error("充值账号出问题了，请联系客服吧");
            return false;
        }
//②、统一下单
        $rtype = db('rechangeconfig')->where("id={$id}")->find();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($rtype['diamond']);
        $input->SetAttach($rtype['money']);
        $orderid = \WxPayConfig::MCHID.date("YmdHis");
        $input->SetOut_trade_no($orderid);
        $input->SetTotal_fee($rtype['money']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($rtype['diamond']);
        $input->SetNotify_url('http://ms.redli366.com/api.php/index/agency/notice');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);


        $data['uid']=$openId;
        $data['money']=$rtype['money'];
        $data['type']=0;
        $data['diamond']=$rtype['diamond'];
        $data['orderid']=$orderid;
        $data['time']=date("Y-m-d H:i:s",time());
        db('recharge')->insert($data);

        $this->assign("jsApiParameters",$jsApiParameters);
        $this->assign("diamond",$rtype['diamond']);
        $this->assign("money",$rtype['money']);
        return view('/pay');
    }

    public function notice()
    {
        \Log::DEBUG("begin notify");
        $notify = new \PayNotifyCallBack();
        $notify->Handle(false);
    }
}